package org.ihelpuoo.weboo.tag.core;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.Tag;

import org.ihelpuoo.lang.SegmentNotFoundException;
import org.ihelpuoo.lang.StringUtils;
import org.ihelpuoo.parser.segment.Segment;
import org.ihelpuoo.parser.segment.SegmentUtils;
import org.ihelpuoo.weboo.tag.WebooTag;

public class ViewTag extends WebooTag
{

	private static final long	serialVersionUID	= -2991710711999591244L;

	private Segment				seg;

	private String				name;
	private String				value;

	public String getName()
	{
		return name;
	}

	public void setName(String pattern)
	{
		this.name = pattern;
	}

	public String getValue()
	{
		return value;
	}

	public void setValue(String value)
	{
		this.value = value;
	}

	@Override
	public void start() throws JspException
	{
		try
		{
			seg = createPattern(name);
		}
		catch (SegmentNotFoundException e)
		{
			throw new JspException(e);
		}
		if (!StringUtils.isBlank(value))
		{
			if (value.startsWith("$"))
				SegmentUtils.fillByObject(seg,pageContext.findAttribute(value.substring(1)));
		}
	}

	Segment getSegment()
	{
		return seg;
	}

	@Override
	public void end() throws JspException
	{
		Tag p = this.getParent();
		while (p != null && !(p instanceof GasketTag))
			p = p.getParent();
		if (null == p)
			write(seg.toString());
		else
			((GasketTag)p).setContent(seg);
	}

}
